package com.example.demo.service;

import com.example.demo.DTO.TokenDTO;
import com.example.demo.api.CarUser;
import com.example.demo.respository.UserRepository;
import com.example.demo.util.JwtToken;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.text.MessageFormat;
import java.util.Map;
import java.util.Optional;

@Service
public class AuthenticationService {
    @Autowired
    private ObjectMapper mapper ;
    @Autowired
   private UserRepository userRepository ;


    @Value("${wx.code2session}")
    private String code2SessionUrl ;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret ;
    private static final String authorization_code="authorization_code";

    public String GetTokenWX(TokenDTO userDate) throws JsonProcessingException {
        String sessioncode=null;
        String url = MessageFormat.format(this.code2SessionUrl,this.appid,this.appsecret,userDate.getPassword());
        System.out.println(url);
        RestTemplate rest = new RestTemplate();
        String sessiontext =  rest.getForObject(url,String.class);
        Map<String,Object> session= mapper.readValue(sessiontext,Map.class);
        System.out.println(sessiontext);
        System.out.println(session);
        return this.registerUser(session);

    }
    private String registerUser (Map<String,Object> session ){
        String openid = (String)session.get("openid");
        if(openid ==null){
            return "wrong";
        }
        Optional <CarUser> carUser ;//此处应该是从数据库种查询
        /*
        Optional<User> userOptional = this.car.findid();
        //user 用户信息 car' 数据口操作接口
            useroptional .ifpersentorelse(consunmmer,runable)

            if(useroptional .ispresent())//TOdo :返回jwt令牌

        User user = user。builder（）.openid().buile()

        userRepositor.save(user) ;
        */
        carUser=Optional.of(userRepository.findById(openid));


        if(carUser.isPresent()){
            //如果存在则返回jwt令牌//TOdo :返回jwt令牌
            return JwtToken.makeToken(carUser.get().getUid(),1);
        }
    //不存在的情况下进行新建 即对用户进行注册
        CarUser user = CarUser.builder().openid(openid).build();//不存在的情况下进行新建
        //此处还要对数据库进行新建操作 userRepositor.save(user) ;
// 写入后再//TOdo :返回jwt令牌 写入用户数据
        Long uid = user.getUid();





        return JwtToken.makeToken(uid,1) ;
    }




}
